//
//  CustomCollectionViewLayout.m
//  15-HomeWork
//
//  Created by dllo on 16/8/3.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "CustomCollectionViewLayout.h"
@interface CustomCollectionViewLayout ()
@property (nonatomic, strong)NSMutableArray<UICollectionViewLayoutAttributes *> *attributesArray;
@property (nonatomic, assign) CGFloat itemWidth;
@property (nonatomic, assign) CGFloat contentWidth;
@end

@implementation CustomCollectionViewLayout
- (instancetype)init {
    self = [super init];
    if (self) {
        _attributesArray = [NSMutableArray array];
        _itemWidth = 100;
        _cellHeight = 40;
        _cellMargin = 5;
        
    }
    return self;
}
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    self = [super init];
    if (self) {
        _attributesArray = [NSMutableArray array];
        _itemWidth = 100;
        _cellHeight = 40;
        _cellMargin = 5;
        
    }
    return self;
   
}
- (CGFloat)cellHeight {
   CGFloat height = CGRectGetHeight(self.collectionView.frame) ;
    return height;
}
- (void)prepareLayout {
    
    
    _contentWidth = 0;
    if (_attributesArray.count != 0) {
        [_attributesArray removeAllObjects];
    }
    
    CGFloat totalWidth = 0.0f;
    for ( int i = 0; i < [self.collectionView numberOfItemsInSection:0]; i++) {
        NSIndexPath *indexpath = [NSIndexPath indexPathForRow:i inSection:0];
        UICollectionViewLayoutAttributes *attribute = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexpath];
        [_attributesArray addObject:attribute];
        
        _itemWidth = [self.delegate collectionView:self.collectionView layout:self height:self.cellHeight widthForItemAtIndexPath:indexpath];
        
        CGFloat x = totalWidth + _cellMargin;
        _contentWidth = x + self.itemWidth + _cellMargin;
        CGFloat y = _cellMargin;
        CGFloat width = self.itemWidth;
        CGFloat height = self.cellHeight;
        attribute.frame = CGRectMake(x, y, width, height);
        totalWidth += width + _cellMargin;
        NSLog(@"%ld",[self.collectionView numberOfItemsInSection:0]);
    }
    
    
    
}

- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect {
    return _attributesArray;
}

- (CGSize)collectionViewContentSize {
   return  CGSizeMake(_contentWidth, _cellHeight);
}
@end
